

package net.jjjshop.job.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.enums.OrderPayTypeEnum;
import net.jjjshop.common.factory.paysuccess.type.PaySuccessTypeFactory;
import net.jjjshop.common.vo.order.PayDataVo;
import net.jjjshop.framework.common.controller.BaseController;
import net.jjjshop.framework.log.annotation.OperationLog;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api(value = "index", tags = {"index"})
@RestController
@RequestMapping("/job/notify")
public class NotifyController extends BaseController {

    @Autowired
    private PaySuccessTypeFactory paySuccessTypeFactory;
    @Autowired
    private WxPayService wxPayService;

    @RequestMapping(value = "/wxPay", method = RequestMethod.POST)
    @OperationLog(name = "wxPay")
    @ApiOperation(value = "微信支付回调", response = String.class)
    public String wxPay(HttpServletRequest request) {
        try {
            log.info("微信支付回调");
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);

            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = result.getOutTradeNo();
            log.info("微信支付回调orderId="+orderId);
            String tradeNo = result.getTransactionId();
            log.info("微信支付回调tradeNo="+tradeNo);
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
            log.info("微信支付回调totalFee="+totalFee);
            JSONObject attach = JSON.parseObject(result.getAttach());
            PayDataVo payDataVo = new PayDataVo();
            payDataVo.setTransaction_id(result.getTransactionId());
            payDataVo.setAttach(attach);
            paySuccessTypeFactory.getFactory(attach.getInteger("orderType"))
                    .onPaySuccess(result.getOutTradeNo(), 10, OrderPayTypeEnum.WECHAT.getValue(), payDataVo);
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
}
